import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//静态路由配置
void main() => runApp(const MyApp3());

//定义根目录Widget
class MyApp3 extends StatelessWidget {
  const MyApp3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        //初始化默认的 Material 组件本地化
        GlobalMaterialLocalizations.delegate,
        //初始化默认的 通用 Widget 组件本地化
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      //当前区域，如果为null则使用系统区域一般用于语言切换
      //传入两个参数，语言代码，国家代码
      //这里配制为中国
      locale: const Locale('zh', 'CN'),
      //定义当前应用程序所支持的语言环境
      supportedLocales: const [
        Locale('en', 'US'), // English 英文
        Locale('zh', 'CN'), // 中文
      ],
      routes: {
        //默认页面
        "/": (BuildContext context) => const Exam217HomePage(),
      },
    );
  }
}
///代码清单2-20 TextField FocusNode 输入焦点控制
///代码路径 lib/code2/code217_TextField.dart
class Exam217HomePage extends StatefulWidget {
  const Exam217HomePage({Key? key}) : super(key: key);

  @override
  State<Exam217HomePage> createState() => _Exam217HomePageState();
}

class _Exam217HomePageState extends State<Exam217HomePage> {
  //创建FocusNode对象实例
  final FocusNode _focusNode = FocusNode();
  @override
  void initState() {
    super.initState();
    //添加listener监听  可以在这里做输入数据的校验
    //对应的TextField失去或者获取焦点都会回调此监听
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        print('得到焦点');
      } else {
        print('失去焦点');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        //隐藏键盘
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      child: Scaffold(
        //页面的头部
        appBar: AppBar(title: const Text("标题")),
        //页面的主内容区
        body: Center(
          child: SizedBox(
            width: 224,
            child: TextField(
              focusNode: _focusNode,
              onEditingComplete: (){
                //点击键盘回车键时的回调
              },
            ),
          ),
        ),
      ),
    );
  }

//页面销毁
  @override
  void dispose() {
    super.dispose();
    //释放
    _focusNode.dispose();
  }

  //获取焦点
  void getFocusFunction(BuildContext context){
    FocusScope.of(context).requestFocus(_focusNode);
  }

  //失去焦点
  void unFocusFunction(){
    _focusNode.unfocus();
  }

  //隐藏键盘而不丢失文本字段焦点：
  void hideKeyBoard(){
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

}
